package com.lan.iot;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.lan.iot.utils.JsonUtil;
import com.lan.iot.utils.OkHttpRequestUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.NCallBack;
import cn.com.newland.nle_sdk.util.NetWorkBusiness;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.lan.iot.Activity_index.numChange;
import static com.lan.iot.Add.DEV_COUNT;

/**
 * Created by Eve on 2022/10/19.
 */
public class RecyAdapter extends RecyclerView.Adapter implements SeekBar.OnSeekBarChangeListener {
    private final int roomid;
    private List<String> mData = new ArrayList<>();
    public List<String> nData = new ArrayList<>();
    public List<String> tagData = new ArrayList<>();
    public List<Integer> imgData = new ArrayList<>();
    private List<Integer> countData = new ArrayList<>();
    private List<Class> intentClass = new ArrayList<>();
    private List<Boolean> haveLo = new ArrayList<>();
    private Context context;
    private boolean lightIsOpen = false;
    private boolean fenweiisopen = false;

    private boolean acdnIsOpen = false;
    private boolean musicIsOpen = false;
    private Boolean cIsOpen = false;
    private Boolean dooropen = false;
    private Class[] classes = {AirCdn.class, Fenwei.class};
    private int[] imgid = {R.drawable.acd, R.drawable.lock_200, R.drawable.light_200, R.drawable.chuanglain200, R.drawable.fenwei};

    //private boolean[] openarry={acdnIsOpen,dooropen,lightIsOpen,cIsOpen};
    public void initdata() {

    }

    public RecyAdapter(Context context, int roomid) {
        this.context = context;
        this.roomid = roomid;
        SharedPreferences settings = context.getSharedPreferences(DEV_COUNT, Context.MODE_PRIVATE);
        int devcount = settings.getInt("devcount", 0);
        for (int i = 1; i <= devcount; i++) {
            if (settings.getInt("roomid" + i, -1) == roomid) {
                countData.add(i);
                nData.add(settings.getString("devname" + i, "未命名设备"));
                if (settings.getInt("devtype" + i, -1) == 0 || settings.getInt("devtype" + i, -1) == 4)
                    haveLo.add(true);
                else haveLo.add(false);
                tagData.add(settings.getString("devtag" + i, ""));
                imgData.add(settings.getInt("devtype" + i, -1));
                switch (settings.getInt("devtype" + i, -1)) {
                    case 0:
                        intentClass.add(classes[0]);
                        break;
                    case 4:
                        intentClass.add(classes[1]);
                        break;
                    default:
                        intentClass.add(null);
                }
            }
        }
        //item中的数据
//        mData.add("客户联系");
//        mData.add("客户群");
//        mData.add("微信客服");
//        mData.add("离职继承");
//        mData.add("群发助手");
//        mData.add("对外收款");

//        nData.add("门锁");
//        nData.add("照明");
//        nData.add("空调");
//        nData.add("窗帘");
//        nData.add("音响");

//        imgData.add(R.drawable.lock_200);
//        imgData.add(R.drawable.light_200);
//        imgData.add(R.drawable.acd);
//        imgData.add(R.drawable.chuanglain200);

//        imgData.add(R.drawable.music);
//        intentClass.add(null);
//
//        intentClass.add(light.class);
//        intentClass.add(AirCdn.class);
//        intentClass.add(null);
//        intentClass.add(null);

//        intentClass.add(Music.class);
//        haveLo.add(false);
//        haveLo.add(false);
//        haveLo.add(true);
//        haveLo.add(false);
//        haveLo.add(false);
//        haveLo.add(true);

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        int layoutId;
        //加载item的布局文件
        layoutId = R.layout.item_one_view_layout;
        init();
        view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        return new VH(view);
    }

    NetWorkBusiness netWorkBusiness;
    public static String token;

    private void init() {
        NetWorkBusiness netWorkBusiness2 = new NetWorkBusiness("", "http://www.nlecloud.com/");
        netWorkBusiness2.signIn(new SignIn("17680316790", "1234567890"), new NCallBack<BaseResponseEntity<User>>(context) {
            @Override
            protected void onResponse(BaseResponseEntity<User> response) {
                netWorkBusiness = new NetWorkBusiness(response.getResultObj().getAccessToken(), "http://www.nlecloud.com/");
                token = response.getResultObj().getAccessToken();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        NlecloudUtil nlecloudUtil=new NlecloudUtil();
//                        nlecloudUtil.gainDevices("596248", token, new NlecloudResponse<List<SensorInfoEntity>>() {
//                            @Override
//                            public void callBack(ResultEntity<List<SensorInfoEntity>> resultEntity) {
//                                List<SensorInfoEntity> resultObj = resultEntity.getResultObj();
//                            }
//                        });
                    }
                }).start();
            }
        });
    }

    public void control(final String deviceID, final String tag, final String val) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                netWorkBusiness.control(deviceID, tag, val, new NCallBack<BaseResponseEntity>(context) {
                    @Override
                    protected void onResponse(BaseResponseEntity response) {
                        if (response.getStatus() != 0) return;//请求失败

                    }
                });
            }
        }).start();
    }

    private void controlDevice(String deviceId, String apiTag, String data) {
        System.out.println("6");
        //发出网络请求
        String SENSOR_DATA_ALL = "http://api.nlecloud.com/Cmds";
        try {
            Map<String, String> valmap = new HashMap<>();
            valmap.put("deviceId", deviceId);
            valmap.put("apiTag", apiTag);
            Response access = OkHttpRequestUtil.postAccess(SENSOR_DATA_ALL, valmap, data, token);
            if (access.isSuccessful()) {
                ResponseBody body = access.body();
                Map map = JsonUtil.toMap(body.string());
                Double status = (double) map.get("Status");
                Message message = new Message();
                if (status == null || status.intValue() != 0.0) {
                    message.arg1 = 0;
                } else {
                    message.arg1 = 1;
                }
                message.obj = map.get("Msg");
                message.what = 0x01;
                handler.sendMessage(message);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0x01:
                    int status = msg.arg1;
                    String msgText = "";
                    if (status == 0) {
                        msgText = "控制失败:" + msg.obj;
                    } else if (status == 1) {
                        msgText = "控制成功:" + msg.obj;
                    }
                    Toast.makeText(context, msgText, Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        final VH vh = (VH) holder;
//        vh.mText.setText(mData.get(position) + "");
        vh.nText.setText(nData.get(position) + "");
        vh.nText.setTextColor(0xff000000);
        vh.img.setImageResource(imgid[imgData.get(position)]);
//        if(imgData.get(position)==0)vh.sw.setChecked(acdnIsOpen);
        switch (imgData.get(position)) {
            case 2:
                vh.sw.setChecked(lightIsOpen);
                break;
            case 0:
                vh.sw.setChecked(acdnIsOpen);
                break;
            case 3:
                vh.sw.setChecked(cIsOpen);
                break;
            case 4:
                vh.sw.setChecked(fenweiisopen);
                break;
            case 1:
                vh.sw.setChecked(dooropen);

        }
        if (position == 0) {

//            vh.sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                @Override
//                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                    numChange("keting"+imgData.get(position),b);
//                    if (b) {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                controlDevice("638233", "dengyi", "1");
//                                //airconditionControl();
//                            }
//                        }).start();
//                    } else {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                controlDevice("638233", "dengyi", "0");
//                                //airconditionControl();
//                            }
//                        }).start();
//                    }
//                }
//            });
        }
//        if(position==2){
//            vh.sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                @Override
//                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                    numChange("ketingkongtiao",b);
//                }
//            });
//        }
//        if (position == 3) {
//            vh.sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                @Override
//                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                    numChange("ketingchuanglian",b);
//                    if (b) {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                controlDevice("638233", "chuang", "1");
//                                //airconditionControl();
//                            }
//                        }).start();
//                    } else {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                controlDevice("638233", "chuang", "0");
//                                //airconditionControl();
//                            }
//                        }).start();
//                    }
//                }
//            });
//        }
        vh.sw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (imgData.get(position) == 2) {
                    final String data = vh.sw.isChecked() ? "1" : "0";
                    System.out.println(data);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            controlDevice("638233", tagData.get(position), data);
                            //airconditionControl();
                        }
                    }).start();
                }
            }
        });
        vh.sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                numChange(roomid + "x" + imgData.get(position), b);
//                System.out.println(tagData.get(position));
                switch (imgData.get(position)) {
                    case 0:
                        acdnIsOpen = b;
                        break;
                    case 4:
                        fenweiisopen = b;
                        break;
                    case 1:
                        dooropen = b;
                        break;
                    case 2:
                        lightIsOpen = b;
                        break;
                    case 3:
                        cIsOpen = b;
                        break;
                }
//                Toast to = Toast.makeText(context, tagData.get(position), Toast.LENGTH_SHORT);
//                to.setGravity(Gravity.CENTER, 0, 0);
//                to.show();
                if (imgData.get(position) != 2) {
                    final String data = b ? "1" : "0";
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            controlDevice("638233", tagData.get(position), data);
                            //airconditionControl();
                        }
                    }).start();
                }
            }
        });
//        if (position == 0) {
//            vh.sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                @Override
//                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                    numChange("ketingmensuo",b);
//                    if (b) {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                controlDevice("638233", "men", "1");
//
//                                //airconditionControl();
//                            }
//                        }).start();
//                    } else {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                controlDevice("638233", "men", "0");
//                                //airconditionControl();
//                            }
//                        }).start();
//                    }
//                }
//            });
//        }
        vh.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                final Dialog dlg;
                final Drawable dr = context.getResources().getDrawable(R.drawable.radius_border);
                dlg = new AlertDialog.Builder(context).create();
                dlg.show();//显示对话框
                Window window = dlg.getWindow();//获取对话框窗口\
                window.setGravity(Gravity.BOTTOM);//设置对话框显示剧中的位置
                window.setContentView(R.layout.delet_dev);//设置对话框布局
                window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

                window.setBackgroundDrawable(dr);
                WindowManager.LayoutParams params = dlg.getWindow()
                        .getAttributes();
                dlg.getWindow().setAttributes(params);
                Button del = window.findViewById(R.id.del);
                del.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        nData.remove(position);
                        intentClass.remove(position);
                        imgData.remove(position);
                        tagData.remove(position);
                        haveLo.remove(position);
                        notifyDataSetChanged();

                        dlg.cancel();
                    }
                });
                return true;
            }
        });
        //设置item的点击事件
        //这里只设置了第一个item的，有需要的自己添加；
        vh.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (imgData.get(position) == 3) {
                    Dialog dlg = null;
                    final Drawable dr = context.getResources().getDrawable(R.drawable.radius_border);
                    dlg = new AlertDialog.Builder(context).create();
                    dlg.show();//显示对话框
                    Window window = dlg.getWindow();//获取对话框窗口\
                    window.setGravity(Gravity.BOTTOM);//设置对话框显示剧中的位置
                    window.setContentView(R.layout.chuanglianbar);//设置对话框布局
                    window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

                    window.setBackgroundDrawable(dr);
                    WindowManager.LayoutParams params = dlg.getWindow()
                            .getAttributes();
                    final int[] qu = new int[1];
                  SeekBar  seekBar = window.findViewById(R.id.appCompatSeekBar);
                    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                        @Override
                        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                            qu[0] =i;
                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {

                        }
                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {
                            if (qu[0] < 13) {
                                seekBar.setProgress(0);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        controlDevice("638233", "chuang", "0");
                                        //airconditionControl();
                                    }
                                }).start();
                            } else if (qu[0] < 38) {
                                seekBar.setProgress(25);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        controlDevice("638233", "ChuangLian", "1");
                                        //airconditionControl();
                                    }
                                }).start();
                            } else if (qu[0] < 63) {
                                seekBar.setProgress(50);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        controlDevice("638233", "ChuangLian", "2");
                                        //airconditionControl();
                                    }
                                }).start();
                            } else if (qu[0] < 88) {
                                seekBar.setProgress(75);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        controlDevice("638233", "ChuangLian", "3");
                                        //airconditionControl();
                                    }
                                }).start();
                            } else {
                                seekBar.setProgress(100);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        controlDevice("638233", "chuang", "1");
                                        //airconditionControl();
                                    }
                                }).start();
                            }
                        }
                    });
                    dlg.getWindow().setAttributes(params);

                } else if (haveLo.get(position)) {
                    Intent intent = new Intent(context, intentClass.get(position));
                    intent.putExtra("name", vh.sw.isChecked());
                    intent.putExtra("roomid", roomid);
                    intent.putExtra("kt", tagData.get(position));
                    context.startActivity(intent);
                } else {
                    Toast to = Toast.makeText(context, "此设备没有控制界面", Toast.LENGTH_SHORT);
                    to.setGravity(Gravity.CENTER, 0, 0);
                    to.show();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return nData.size();
    }


    public void refreshLight(boolean isOpen) {
        lightIsOpen = isOpen;
        notifyDataSetChanged();
    }

    public void refreshAcdn(boolean isOpen) {
        acdnIsOpen = isOpen;
        notifyDataSetChanged();
    }

    public void refreshMusic(boolean isOpen) {
        musicIsOpen = isOpen;
        notifyDataSetChanged();
    }

    public void refreshefenwei(boolean isOpen) {
        fenweiisopen = isOpen;
        notifyDataSetChanged();
    }

    public void refreshc(Boolean msg_a) {
        cIsOpen = msg_a;
        notifyDataSetChanged();
    }

    public void refreshdoor(Boolean msg_door) {
        dooropen = msg_door;
        notifyDataSetChanged();
    }


    public void adddev(String msg_add, String devtag, int devtype) {
        nData.add(msg_add);
        if (devtype == 0 || devtype == 4) haveLo.add(true);
        else haveLo.add(false);
        tagData.add(devtag);
        imgData.add(devtype);
        switch (devtype) {
            case 0:
                intentClass.add(classes[0]);
                break;
            case 4:
                intentClass.add(classes[1]);
                break;
            default:
                intentClass.add(null);
        }
        notifyDataSetChanged();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        quota = i;
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    private int quota;//当前滑动到的值

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        setSeekBar(quota);
    }

    private void setSeekBar(int i) {
//        if (i < 13) {
//            seekBar.setProgress(0);
//        } else if (i < 38) {
//            seekBar.setProgress(25);
//        } else if (i < 63) {
//            seekBar.setProgress(50);
//        } else if (i < 88) {
//            seekBar.setProgress(75);
//        } else {
//            seekBar.setProgress(100);
//        }
    }

    //初始化item布局文件的各个控件
    class VH extends RecyclerView.ViewHolder {
        TextView mText, nText;
        ImageView img;
        Switch sw;

        public VH(@NonNull View itemView) {
            super(itemView);
            sw = itemView.findViewById(R.id.sw);
            nText = itemView.findViewById(R.id.text1);
//            nText.setText("111");
            img = itemView.findViewById(R.id.img);
        }
    }


}
